package com.woniuxy.java106crm.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class CustomerAlertScheduler implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            // 定义任务
            JobDetail job = JobBuilder.newJob(CustomerAlertJob.class)
                    .withIdentity("customerAlertJob", "group1")
                    .build();

//            // 定义触发器，每五秒执行一次
//            Trigger trigger = TriggerBuilder.newTrigger()
//                    .withIdentity("customerAlertTrigger", "group1")
//                    .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(5))
//                    .build();

            // 定义触发器，每周六凌晨02:00执行
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("customerAlertTrigger", "group1")
                    .withSchedule(CronScheduleBuilder.weeklyOnDayAndHourAndMinute(DateBuilder.SATURDAY, 2, 0))
                    .build();

            // 将任务和触发器添加到调度器中
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}